package cn.liujianbo.example.base.nio;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * nio 读取文件
 * @author 刘建波
 * @date 2021-01-13 16:25
 */
public class ReadFileDemo {

    /**
     * io   面向 字节流  字符流 操作
     * nio  面向 channel  buffer 操作
     *
     * @param args
     */
    public static void main(String[] args) {
        // 获取 classpath下 static/1.txt的文件 url
        URL resource = ReadFileDemo.class.getClassLoader().getResource("static/1.txt");
        try {
            RandomAccessFile aFile = new RandomAccessFile(resource.getFile(), "r");
            // 申请 channel
            FileChannel channel = aFile.getChannel();
            // 申请 缓冲区
            ByteBuffer byteBuffer = ByteBuffer.allocate((int)aFile.length());

            channel.read(byteBuffer);
            byteBuffer.flip();
            System.out.println(new String(byteBuffer.array(), StandardCharsets.UTF_8));
            byteBuffer.clear();
            aFile.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
